{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "583c36f1-ad7e-4ec4-998b-76d0d301f582",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "这是侯霖肖的python作业\n",
      "\n",
      "Python是一种广泛使用的高级编程语言，具有以下特点：\n",
      "简洁易读、高级语言、跨平台、解释性语言等\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# 创建一个测试文件\n",
    "class1=\"\"\"这是侯霖肖的python作业\n",
    "#你好\n",
    "Python是一种广泛使用的高级编程语言，具有以下特点：\n",
    "简洁易读、高级语言、跨平台、解释性语言等\n",
    "#你们好\n",
    "#这是第五次作业\"\"\"\n",
    "\n",
    "#将测试内容写入文件\n",
    "with open('class1.txt', 'w') as file:\n",
    "    file.write(class1)\n",
    "\n",
    "# 读取文件并忽略每行中以#之后的内容\n",
    "with open('class1.txt', 'r') as file:\n",
    "    for line in file:\n",
    "        cleaned_line = line.split('#')[0].rstrip()\n",
    "        print(cleaned_line)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "b7790351-14e7-4db3-b1a5-035cae288eb0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "请输入数字N： 4\n",
      "请输入文件名F： class1.txt\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "这是侯霖肖的python作业\n",
      "#你好\n",
      "Python是一种广泛使用的高级编程语言，具有以下特点：\n",
      "简洁易读、高级语言、跨平台、解释性语言等\n"
     ]
    }
   ],
   "source": [
    "# 提示用户输入数字N和文件名F\n",
    "N = int(input(\"请输入数字N：\"))\n",
    "F = input(\"请输入文件名F：\")\n",
    "\n",
    "# 读取文件并显示前N行\n",
    "try:\n",
    "    with open(F, 'r') as file:\n",
    "        for i, line in enumerate(file):\n",
    "            if i < N:\n",
    "                print(line, end='')  # end='' 防止print函数自动添加额外的换行符\n",
    "            else:\n",
    "                break\n",
    "except FileNotFoundError:\n",
    "    print(f\"错误：文件 '{F}' 未找到。\")\n",
    "except Exception as e:\n",
    "    print(f\"发生错误：{e}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "1483e462-9ee1-44ff-8140-b10e1ec7a6d8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello word\n",
      "How are you\n",
      "I am fun thank\n",
      "and you\n",
      "what happend\n"
     ]
    }
   ],
   "source": [
    "# 创建一个测试文件\n",
    "class2=\"\"\"hello word\n",
    "How are you\n",
    "I am fun thank\n",
    "and you\n",
    "what happend\n",
    "\"\"\"\n",
    "\n",
    "#将测试内容写入文件\n",
    "with open('class2.txt', 'w') as file:\n",
    "    file.write(class2)\n",
    "\n",
    "# 读取文件并忽略每行中以#之后的内容\n",
    "with open('class2.txt', 'r') as file:\n",
    "    for line in file:\n",
    "        cleaned_line = line.split('#')[0].rstrip()\n",
    "        print(cleaned_line)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "eda34fca-e302-47b2-a4be-f319e987a62d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "请输入文件名F： test2.txt\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "这是一个测试案例\n",
      "每次显示25行\n",
      "这是第3行\n",
      "4\n",
      "5\n",
      "hello word\n",
      "7\n",
      "8\n",
      "9\n",
      "10\n",
      "11\n",
      "12\n",
      "13\n",
      "14\n",
      "15行\n",
      "16\n",
      "17\n",
      "18\n",
      "19\n",
      "20\n",
      "21\n",
      "22\n",
      "23\n",
      "24\n",
      "这是第25行\n",
      "\n",
      "按下 'Y' 继续显示，或按其他键退出:\n"
     ]
    },
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      " y\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "这是第26行\n",
      "27\n",
      "28\n",
      "29\n",
      "project\n",
      "ending\n",
      "按下 'Y' 继续显示，或按其他键退出:\n"
     ]
    },
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      " \n"
     ]
    }
   ],
   "source": [
    "def read_file_in_chunks(filename, chunk_size=25):\n",
    "    encodings = ['utf-8', 'gbk', 'utf-16', 'utf-16le', 'utf-16be']\n",
    "    for encoding in encodings:\n",
    "        try:\n",
    "            with open(filename, 'r', encoding=encoding) as file:\n",
    "                while True:\n",
    "                    lines = list(islice(file, chunk_size))\n",
    "                    if not lines:\n",
    "                        break\n",
    "                    for line in lines:\n",
    "                        print(line, end='')\n",
    "                    print(\"\\n按下 'Y' 继续显示，或按其他键退出:\")\n",
    "                    if input().upper() != 'Y':\n",
    "                        return\n",
    "        except FileNotFoundError:\n",
    "            print(f\"错误：文件 '{filename}' 未找到。\")\n",
    "            return\n",
    "        except UnicodeDecodeError:\n",
    "            print(f\"尝试使用编码 {encoding} 解码文件失败，尝试下一个编码...\")\n",
    "            continue\n",
    "        except Exception as e:\n",
    "            print(f\"发生错误：{e}\")\n",
    "            return\n",
    "\n",
    "from itertools import islice\n",
    "\n",
    "# 提示用户输入文件名\n",
    "filename = input(\"请输入文件名F：\")\n",
    "\n",
    "# 调用函数以25行块的形式读取文件\n",
    "read_file_in_chunks(filename)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "b01ca575-8ab6-4cbc-b2c9-20f5124cc9d4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "请输入第一个文件的路径： class1.txt\n",
      "请输入第二个文件的路径： class2.txt\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "文件不同：第 1 行，第 1 列\n"
     ]
    }
   ],
   "source": [
    "def compare_files(file1, file2):\n",
    "    encodings = ['utf-8', 'gbk', 'utf-16', 'utf-16le', 'utf-16be']\n",
    "    for encoding in encodings:\n",
    "        try:\n",
    "            with open(file1, 'r', encoding=encoding) as f1, open(file2, 'r', encoding=encoding) as f2:\n",
    "                line_num = 1\n",
    "                for line1, line2 in zip(f1, f2):\n",
    "                    if line1 != line2:\n",
    "                        col_num = 1\n",
    "                        for char1, char2 in zip(line1, line2):\n",
    "                            if char1 != char2:\n",
    "                                print(f\"文件不同：第 {line_num} 行，第 {col_num} 列\")\n",
    "                                return\n",
    "                            col_num += 1\n",
    "                        # 检查哪个文件有额外的字符\n",
    "                        if len(line1) > len(line2):\n",
    "                            print(f\"文件不同：第 {line_num} 行，第 {col_num} 列\")\n",
    "                        elif len(line1) < len(line2):\n",
    "                            print(f\"文件不同：第 {line_num} 行，第 {col_num} 列\")\n",
    "                        return\n",
    "                    line_num += 1\n",
    "                \n",
    "                # 检查是否有剩余的行\n",
    "                extra_lines = f1.readlines() + f2.readlines()\n",
    "                if extra_lines:\n",
    "                    print(f\"文件不同：第 {line_num} 行，第 1 列\")\n",
    "                else:\n",
    "                    print(\"两个文件的内容是相同的。\")\n",
    "                break\n",
    "        except UnicodeDecodeError:\n",
    "            continue\n",
    "        except FileNotFoundError as e:\n",
    "            print(f\"错误：{e}\")\n",
    "            return\n",
    "    else:\n",
    "        print(\"错误：尝试了多种编码，但都无法解码文件。\")\n",
    "\n",
    "# 使用示例\n",
    "file1 = input(\"请输入第一个文件的路径：\")\n",
    "file2 = input(\"请输入第二个文件的路径：\")\n",
    "compare_files(file1, file2)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "7dc65285-77b0-4e58-b670-03a06127287f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "([('you', 2),\n",
       "  ('hello', 1),\n",
       "  ('word', 1),\n",
       "  ('how', 1),\n",
       "  ('are', 1),\n",
       "  ('i', 1),\n",
       "  ('am', 1),\n",
       "  ('fun', 1),\n",
       "  ('thank', 1),\n",
       "  ('and', 1),\n",
       "  ('what', 1),\n",
       "  ('happend', 1)],\n",
       " 13)"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 接下来，我将读取这个文本文件，并统计其中的单词数。\n",
    "from collections import Counter\n",
    "import re\n",
    "\n",
    "# 读取文件内容\n",
    "with open('class2.txt', 'r') as file:\n",
    "    content = file.read()\n",
    "\n",
    "# 使用正则表达式分割单词，并统计单词出现的次数\n",
    "words = re.findall(r'\\b\\w+\\b', content.lower())  # 转换为小写以避免大小写差异\n",
    "word_count = Counter(words)\n",
    "\n",
    "# 输出单词总数\n",
    "total_words = len(words)\n",
    "word_count.most_common(), total_words"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "41773452-5625-4123-9b01-e03306d96523",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['you', 'happend', 'fun', 'what', 'how', 'hello', 'and', 'am', 'you', 'thank']"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import random\n",
    "\n",
    "# 随机输出其中的 10 个单词\n",
    "random_words = random.sample(words, 10)\n",
    "random_words"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
